<script setup lang="ts">
import { message } from "@/utils/message";
import { ref } from "vue";
import { formRules } from "../utils/rule";
import { FormProps } from "../utils/types";
import { useColumns } from "./columns";
const { kcpdColumns } = useColumns();

import { getCheckSearch } from "@/api/stock/check";

const props = withDefaults(defineProps<FormProps>(), {
  ckList: undefined
});

const tableList = ref([]);
const ruleFormRef = ref();
const newForm = ref<any>({});

const depositoryChange = async () => {
  let tempList = [];
  if (newForm.value.depositoryId) {
    let params = {
      inventoryType: 1,
      depositoryId: newForm.value.depositoryId
    };
    let { data } = await getCheckSearch(params);
    tempList = [data];
  }
  tableList.value = tempList;
};

function getForm() {
  return new Promise(resolve => {
    let obj: any = {
      isPass: false,
      params: {}
    };
    ruleFormRef.value.validate(async valid => {
      if (!valid) {
        resolve(obj);
        return;
      }

      let tableData = tableList.value[0];
      let postCount = tableData.postCount;
      if (!postCount && postCount !== 0) {
        resolve(obj);
        return message("请输入盘点后库存", { type: "warning" });
      }

      obj.params = {
        inventoryType: 1,
        atCount: tableData.atCount,
        depositoryId: newForm.value.depositoryId,
        postCount: tableData.postCount,
        varianceNum: Number(tableData.postCount) - Number(tableData.atCount)
      };
      obj.isPass = true;
      console.log("par", obj.params);
      resolve(obj);
    });
  });
}

function getRef() {
  return ruleFormRef.value;
}

defineExpose({ getRef, getForm });
</script>

<template>
  <el-form
    ref="ruleFormRef"
    :model="newForm"
    :rules="formRules"
    label-width="90px"
    class="pd-form"
  >
    <el-form-item label="选择仓库" prop="depositoryId">
      <el-select
        v-model="newForm.depositoryId"
        clearable
        filterable
        placeholder="请选择"
        class="!w-[250px]"
        @change="depositoryChange"
      >
        <el-option
          v-for="item in props.ckList"
          :key="item.id"
          :label="item.depositoryName"
          :value="item.id"
        />
      </el-select>
    </el-form-item>
    <pure-table
      row-key="id"
      align-whole="center"
      :header-cell-style="{
        background: 'var(--el-fill-color-light)',
        color: 'var(--el-text-color-primary)'
      }"
      :data="tableList"
      :columns="kcpdColumns"
    />
  </el-form>
</template>

<style scoped lang="scss">
.pd-form {
  margin: 10px 10px 25px;
}
</style>
